<template>
  <div style="margin-top: 15%; padding: 20px">
    <a-form ref="formRef" :model="logData" v-bind="formItemLayout" @finish="handleLogin">
        <a-form-item label="邮箱" name="email" :rules="[{ type: 'email', message: '非法邮箱' }, { required: true, message: '请输入邮箱' }, { validator: validateEmail  , trigger: 'change' }]" >
          <a-input v-model:value="logData.email" />
        </a-form-item>
        <a-form-item has-feedback label="密码" name="passwd" :rules="[{ required: true, message: '请输入密码' }, { validator: validatePass, trigger: 'change' }]" >
          <a-input-password v-model:value="logData.passwd" autocomplete="off" />
        </a-form-item>
      <a-form-item html-type="submit" v-bind="tailFormItemLayout">
        <a-button :disabled="disableSubmit" type="primary" html-type="submit" size="default" ghost style="width:120px"><LoadingOutlined v-show="disableSubmit"/>登录</a-button>
        <a-button type="link" style="margin-left: 20px" href="/register">注&nbsp;册&nbsp;上&nbsp;岸</a-button>
        <a-button type="link"  href="/user/modify/0">忘记密码</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts">
import { Form, Input, Button, message } from 'ant-design-vue'
// import { storage, longStorage } from '@/model'
import type { FormInstance } from 'ant-design-vue'
import { reactive, ref } from 'vue'
import { login } from '@/service'
import { useRouter } from 'vue-router'
import { LoadingOutlined } from '@ant-design/icons-vue'
import { tokenName, userName, role, timeStamp } from '@/utils/constants'

export default {
  name: 'ALogin',
  components: {
    LoadingOutlined,
    AForm: Form,
    AFormItem: Form.Item,
    AInput: Input,
    AButton: Button,
    AInputPassword: Input.Password
  },
  setup () {
    const formRef = ref<FormInstance>()
    const logData = reactive({
      email: '',
      passwd: ''
    })
    const router = useRouter()
    const disableSubmit = ref<boolean>(false)
    const formItemLayout = {
      labelCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 3, offset: 2 },
        md: { span: 4, offset: 2 },
        xl: { span: 3, offset: 6 },
        xxl: { span: 4, offset: 5 }
      },
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 16 },
        md: { span: 15 },
        xl: { span: 10 },
        xxl: { span: 8 }
      }
    }

    const tailFormItemLayout = {
      wrapperCol: {
        xs: { span: 22, offset: 0 },
        sm: { span: 18, offset: 4 },
        md: { span: 18, offset: 6 },
        xl: { span: 10, offset: 12 },
        xxl: { span: 6, offset: 12 }
      }
    }

    const validateEmail = async () => {
      if (logData.email.length > 30) {
        return Promise.reject(new Error('邮箱太长啦'))
      }
      return Promise.resolve()
    }
    const validatePass = async () => {
      if (logData.passwd.length > 15) {
        return Promise.reject(new Error('密码最多15位'))
      }
      return Promise.resolve()
    }

    const handleLogin = (value: { email: string, passwd: string }) => {
      disableSubmit.value = true
      login(value)
        .then((response) => {
          if (response.status !== 200) {
            message.error('返回状态码出错')
            return
          }
          const resp = response.data
          if (resp.code === 0) {
            if (resp.data !== null) {
              const d = resp.data
              const k = d.sc + d.p + d.ot + d.w
              const t = d.ct
              // 设置session
              sessionStorage.setItem(role, d.er)
              sessionStorage.setItem(tokenName, k)
              sessionStorage.setItem(userName, d.uname)
              // 长期存储
              localStorage.setItem(role, d.er)
              localStorage.setItem(tokenName, k)
              localStorage.setItem(userName, d.uname)
              localStorage.setItem(timeStamp, t)

              message.info('登录成功,前往首页...', 0.5)

              setTimeout(() => {
                router.push({ name: 'workGround', params: { token: k } })
              }, 800)
            } else {
              message.error('出现错误')
            }
          } else {
            message.error('登录失败请检查，用户名和密码')
            disableSubmit.value = false
          }
        })
        .catch((err) => {
          message.error('请求出错')
          console.log(err)
          disableSubmit.value = false
        })
    }

    return {
      formRef,
      logData,
      formItemLayout,
      tailFormItemLayout,
      disableSubmit,
      validateEmail,
      validatePass,
      handleLogin
    }
  },
  created () {
    document.body.style.backgroundColor = '#F5F5F5'
  },
  beforeUnmount () {
    document.body.style.backgroundColor = ''
  }
}
</script>

<style scoped>

</style>
